[assembly: System.Reflection.AssemblyDescription("QA-Tools-11")]

namespace QAToolsAddin
{
    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.Xml;
    using Microsoft.Office.Core;
    using QAToolsAddin.GenericDialogs;
    using Excel = Microsoft.Office.Interop.Excel;

    [GuidAttribute("FA5EC8F4-B134-45FB-9075-746D14E5372F"), ComVisible(true)]
    public interface IConnect : Extensibility.IDTExtensibility2
    {
        void Test();
    }

    [GuidAttribute("5E934B55-8283-4167-B273-7F2EBF363A52"), ProgId("QAToolsAddin.Connect"), ComVisible(true), ComDefaultInterface(typeof(IConnect)), ClassInterface(ClassInterfaceType.None)]
    public partial class Connect : ConnectBase, IConnect
	{
        private Dictionary<string, CommandBarButton> _buttons;

        public Connect()
		{
		}

        public override void OnStartupComplete()
        {           
            _excelapp.ScreenUpdating = false;
            try {
                var xmldoc = new XmlDocument();
                xmldoc.LoadXml(Properties.Resources.Ribbon);
                _buttons = AddCommandBarButtons(xmldoc.DocumentElement.FirstChild.FirstChild.ChildNodes);
                var btUndo = _buttons["btUndo_Click"];
                Undo.SetButtonEnabled += delegate(bool value) { btUndo.Enabled = value; };
            } catch (Exception ex) {
                MsgBox.ShowError(_excelapp, ex.Message);
            } finally {
                _excelapp.ScreenUpdating = true;
            }
		}

        private stdole.IPictureDisp GetPicture(string imageName) {
            //http://support.microsoft.com/kb/288771
            var image = (System.Drawing.Bitmap)Properties.Resources.ResourceManager.GetObject(imageName);
            return image != null ? PictureConverter.ImageToPictureDisp(image) : null;
        }

        private Dictionary<string, CommandBarButton> AddCommandBarButtons(XmlNodeList nodes) {
            Dictionary<string, CommandBarButton> buttons = new Dictionary<string, CommandBarButton>();
            AddCommandBarButtons_recursive(nodes, buttons, null, false);
            return buttons;
        }

        private void AddCommandBarButtons_recursive(XmlNodeList nodes, Dictionary<string, CommandBarButton> buttons, CommandBarPopup cmdbar, bool beginGroup) {
            if (nodes == null) return;
            foreach (XmlNode node in nodes) {
                var nodeName = node.Name;
                var nodeLabel = node.Attributes["label"].Value;
                switch(nodeName){
                    case "tab" :
                        var oCommandBars = (CommandBars)_excelapp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, _excelapp, null);
                        var btTab = (CommandBarPopup)oCommandBars["Worksheet Menu Bar"].Controls.Add(MsoControlType.msoControlPopup, Type.Missing, Type.Missing, Type.Missing, true);
                        btTab.Caption = nodeLabel;
                        AddCommandBarButtons_recursive(node.ChildNodes, buttons, btTab, false);
                        break;
                    case "group" :
                        AddCommandBarButtons_recursive(node.ChildNodes, buttons, cmdbar, true);
                        break;
                    case "menu" :
                        var btMenu = (CommandBarPopup)cmdbar.Controls.Add(MsoControlType.msoControlPopup, Type.Missing, Type.Missing, Type.Missing, true);
                        btMenu.Caption = nodeLabel;
                        if (beginGroup) {
                            btMenu.BeginGroup = true;
                            beginGroup = false;
                        }
                        AddCommandBarButtons_recursive(node.ChildNodes, buttons, btMenu, false);
                        break;
                    case "button" :
                        var nodeId = node.Attributes["id"].Value;
                        CommandBarButton bt = (CommandBarButton)cmdbar.Controls.Add(MsoControlType.msoControlButton, Type.Missing, Type.Missing, Type.Missing, true);
                        buttons.Add(nodeId, bt);
                        bt.Caption = nodeLabel;
                        var imageAttribute = node.Attributes["image"];
                        if (imageAttribute != null) {
                            var image = GetPicture(imageAttribute.Value);
                            if (image != null)
                                bt.Picture = image;
                            var imagemsk = GetPicture(imageAttribute.Value + "_msk");
                            if (imagemsk != null)
                                bt.Mask = imagemsk;
                        }
                        var enabledAttribute = node.Attributes["enabled"];
                        if (enabledAttribute != null)
                            _commands.SetControlEnabled(nodeId, bool.Parse(enabledAttribute.Value));
                        bt.Enabled = _commands.GetControlEnabled(nodeId);
                        var screentip = node.Attributes["screentip"];
                        if (screentip != null) bt.TooltipText = node.Attributes["screentip"].Value;
                        if (beginGroup) {
                            bt.BeginGroup = true;
                            beginGroup = false;
                        }
                        bt.Click += delegate { _commands.InvokeAction(nodeId); };
                        break;
                }
            }
        }

	}
}